const config = require('../config');
const log = require('./logger');
const got = require('got');
const QuickLRU = require('quick-lru');

const size = config.get('albumCoverSize', 1000);

const lru = new QuickLRU({ maxSize: 100 });
/**
 * Download the album cover of a track.
 *
 * @param {Object} trackInfos
 */
const downloadAlbumCover = async (trackInfos) => {
  if (!trackInfos.ALB_PICTURE) return null;

  try {
    const { body, fromCache } = await got(
      `http://e-cdn-images.dzcdn.net/images/cover/${trackInfos.ALB_PICTURE}/${size}x${size}.jpg`,
      {
        responseType: 'buffer',
        cache: lru,
      }
    );
    log.debug(`Fetched cover for ${trackInfos.SNG_TITLE}, cache: ${fromCache}`);
    return body;
  } catch (err) {
    log.debug(`Failed to download cover for ${trackInfos.SNG_TITLE}, #${trackInfos.SNG_ID} Error: ${err.message}`);
    return null;
  }
};

module.exports = downloadAlbumCover;
